from functools import wraps
from flask import request, jsonify
from app.utils.cache import RedisCache
from app.utils.errors import APIError
import time

def rate_limit(limit=60, window=60):
    """
    速率限制装饰器
    :param limit: 允许的最大请求次数
    :param window: 时间窗口（秒）
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                cache = RedisCache()
                key = f'rate_limit:{request.remote_addr}:{f.__name__}'
                
                # 获取当前计数
                current = cache.get(key)
                if current is None:
                    cache.set(key, 1, window)
                    current = 1
                else:
                    current = int(current)
                    if current >= limit:
                        raise APIError(
                            message="Too many requests",
                            error_code=429
                        )
                    cache.incr(key)
                
                return f(*args, **kwargs)
            except RuntimeError as e:
                # Redis 连接错误时，暂时禁用速率限制
                return f(*args, **kwargs)
                
        return decorated_function
    return decorator 